/**
 * 封装常用的限定范围时间插件
 * 减少多余的代码提高代码复用性
 * {RangePickerDom()}和<RangePickerDom />的区别在与<RangePickerDom />每次更新会被卸载掉然后重新渲染针对onChange事件
 * <InputRender />.type() === InputRender()
 */
import React, { useState } from "react";

import { DatePicker } from "antd";

import { RangePickerProps } from "antd/lib/date-picker";

import moment from "moment";

type date = [moment.Moment, moment.Moment];

const type = {
  days: 'date',
  months: 'month',
  quarters: 'quarter',
  years: 'year'
}

export default ({
  defaultvalue = [moment().subtract(15, "days"), moment()],
  rangeType = "days",
  range = 15
}: {
  defaultvalue?: date;
  /** @rangeType 范围类型 不是必传默认为按日 */ rangeType?: moment.unitOfTime.DurationConstructor;
  /** @range 范围 不是必传默认为14天 */ range?: number;
}): {
  DOM: (e: RangePickerProps) => JSX.Element;
  date: date;
  setDate: (e: date) => void;
} => {
  const [chooseDate, setChooseDate] = useState<date>(defaultvalue);
  const [dates, setDates] = useState([]);
  const [hackValue, setHackValue] = useState();
  const disabledDate = current => {
    if (!dates || dates.length === 0) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], rangeType) > range;
    const tooEarly = dates[1] && dates[1].diff(current, rangeType) > range;
    return tooEarly || tooLate;
  };

  const onOpenChange = open => {
    if (open) {
      setHackValue([]);
      setDates([]);
    } else {
      setHackValue(undefined);
    }
  };
  return {
    date: chooseDate,
    setDate: setChooseDate,
    DOM: ({...otherprops}: RangePickerProps) => {
      return (
        <DatePicker.RangePicker
          picker={type[rangeType]}
          allowClear={false}
          onChange={setChooseDate}
          value={hackValue || chooseDate}
          disabledDate={disabledDate}
          onCalendarChange={val => setDates(val)}
          onOpenChange={onOpenChange}
          {...otherprops}
        />
      );
    }
  };
};
